package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("DetectstandardService")
@Transactional

public class DetectstandardServiceImpl extends CmiEmaService implements DetectstandardService {
	public DetectstandardServiceImpl() {
	}

	@Transactional
	public Detectstandard saveDetectstandard(Detectstandard detectstandard) {

		if (detectstandard.getId() == null) {
			Feature feature = featureDAO.findFeatureById(detectstandard.getFeature().getId());
			Food food = foodDAO.findFoodById(detectstandard.getFood().getId());
			Unit unit = unitDAO.findUnitById(detectstandard.getUnit().getId());

			Detectstandard existingDetectstandard = detectstandardDAO
					.findDetectstandardByPhysicalPrimaryKey(food.getId(), feature.getId(), detectstandard.getDate());

			detectstandard.setFeature(feature);
			detectstandard.setFood(food);
			detectstandard.setUnit(unit);

			if (isEquals(detectstandard, existingDetectstandard)) {
				return existingDetectstandard;
			}

			detectstandard = detectstandardDAO.store(detectstandard);
			detectstandardDAO.flush();

		} else {
			Detectstandard existingDetectstandard = detectstandardDAO
					.findDetectstandardByPrimaryKey(detectstandard.getId());

			detectstandard = detectstandardDAO.store(detectstandard);
			detectstandardDAO.flush();
		}

		return detectstandard;
	}

	public void deleteDetectstandard(Detectstandard detectstandard) {
		detectstandardDAO.remove(detectstandard);
		detectstandardDAO.flush();
	}

	@Transactional
	public void deleteDetectstandards(Set<Integer> deleteDetectstandardsId) {
		Query query = detectstandardDAO.createNamedQuery("deleteDetectstandardsById", -1, -1);
		query.setParameter(1, deleteDetectstandardsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Detectstandard> loadDetectstandards() {
		return detectstandardDAO.findAllDetectstandards();

	}

	@Transactional
	public Set<Detectstandard> loadReferenceDetectstandards(Set<Detectstandard> detectstandards) {
		Iterator<Detectstandard> detectstandardsIterator = detectstandards.iterator();
		Set<Detectstandard> referencedDetectstandards = new HashSet<>();
		while (detectstandardsIterator.hasNext()) {
			Detectstandard currentDetectstandard = detectstandardsIterator.next();

		}
		return referencedDetectstandards;
	}

	public Set<Detectstandard> loadDetectstandardsByIdSet(Set<Integer> detectstandardIdSet) {

		Iterator<Integer> detectstandardIdIterator = detectstandardIdSet.iterator();
		Set<Detectstandard> detectstandardSet = new HashSet<>();
		while (detectstandardIdIterator.hasNext()) {
			Integer id = detectstandardIdIterator.next();
			Detectstandard currentDetectstandard = detectstandardDAO.findDetectstandardById(id);
			detectstandardSet.add(currentDetectstandard);
		}
		return detectstandardSet;
	}

	@Transactional
	public List<Detectstandard> findAllDetectstandards(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Detectstandard>(detectstandardDAO.findAllDetectstandards(startResult, maxRows));
	}

	@Transactional
	public Detectstandard findDetectstandardByPrimaryKey(Integer id) {
		return detectstandardDAO.findDetectstandardByPrimaryKey(id);
	}

	@Transactional
	public Integer countDetectstandards() {
		return ((Long) detectstandardDAO.createQuerySingleResult("select count(o) from Detectstandard o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countDetectstandards(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Detectstandard.class);
		return ((Long) detectstandardDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countDetectstandardsByName(String queryName) {
		Query query = detectstandardDAO.createNamedQuery("countDetectstandardsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countDetectstandardsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Detectstandard.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadDetectstandardObjectReferencedSet(Detectstandard detectstandard) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (detectstandard.getFeature() != null) {

			Set<Integer> featureIds = new HashSet<Integer>();
			featureIds.add(detectstandard.getFeature().getId());
			objectReferencedSetMap.put("featureIds", featureIds);
		}
		if (detectstandard.getFood() != null) {

			Set<Integer> foodIds = new HashSet<Integer>();
			foodIds.add(detectstandard.getFood().getId());
			objectReferencedSetMap.put("foodIds", foodIds);
		}
		if (detectstandard.getUnit() != null) {

			Set<Integer> unitIds = new HashSet<Integer>();
			unitIds.add(detectstandard.getUnit().getId());
			objectReferencedSetMap.put("unitIds", unitIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadDetectstandardClassReferencedSet(Detectstandard detectstandard) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("features", featureDAO.findAllFeatures());
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());
		classReferencedSetMap.put("units", unitDAO.findAllUnits());

		return classReferencedSetMap;
	}

	public boolean isEquals(Detectstandard detectstandard, Object obj) {
		if (obj == detectstandard)
			return true;
		if (!(obj instanceof Detectstandard))
			return false;
		Detectstandard comparedDetectstandard = (Detectstandard) obj;
		if (!CheckPropertyEqual(detectstandard.getFood().getId(), comparedDetectstandard.getFood().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(detectstandard.getFeature().getId(), comparedDetectstandard.getFeature().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(detectstandard.getDate(), comparedDetectstandard.getDate())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

